import axios from 'axios'
import { ElLoading } from 'element-plus'

// 获取AI服务基础URL
const getAIBaseURL = () => {
  // 开发环境使用代理，生产环境直接使用后端地址
  return import.meta.env.VITE_AI_LEARNING_API || 'http://47.113.221.252:8107'
}

// 创建AI服务专用的axios实例
const aiService = axios.create({
  timeout: 30000, // 30秒超时，AI响应可能较慢
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 记录最近点击的按钮元素，便于局部 Loading
let lastClickedButtonEl = null;
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  document.addEventListener(
    'mousedown',
    (e) => {
      const target = e.target instanceof Element ? e.target : null;
      const epButton = target?.closest?.('._button, .el-button') || null;
      const nativeButton = !epButton && target && target.tagName === 'BUTTON' ? target : null;
      lastClickedButtonEl = (epButton || nativeButton) || null;
    },
    true
  );
}

// 全局遮罩管理（跨模块共享）
const overlayKey = '__GlobalLoadingOverlay'
function getOverlayState() {
  try {
    const w = window
    if (!w[overlayKey]) {
      w[overlayKey] = { instance: null, count: 0 }
    }
    return w[overlayKey]
  } catch (_) {
    return { instance: null, count: 0 }
  }
}

// 请求拦截器
aiService.interceptors.request.use(
  config => {
    // 构建完整URL
    const baseURL = getAIBaseURL()
    config.url = baseURL + config.url
    
    // 添加认证token（如果需要）
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 在按钮上展示局部加载动画（默认开启，可通过 config.noBtnLoading 或 headers.noBtnLoading 关闭）
    try {
      const disableBtnLoading = config.noBtnLoading === true || (config.headers || {}).noBtnLoading === true;
      if (!disableBtnLoading && typeof window !== 'undefined' && typeof document !== 'undefined') {
        let buttonEl = lastClickedButtonEl;
        if (!buttonEl) {
          const activeEl = document.activeElement;
          if (activeEl && activeEl instanceof Element) {
            buttonEl = activeEl.closest?.('.el-button') || (activeEl.tagName === 'BUTTON' ? activeEl : null);
          }
        }
        if (buttonEl) {
          const loadingInstance = ElLoading.service({
            target: buttonEl,
            text: '加载中',
            background: 'transparent',
            fullscreen: false,
          });
          Object.defineProperty(config, '__btnLoading', {
            value: loadingInstance,
            enumerable: false,
            configurable: true,
            writable: true,
          });
        }
      }
    } catch (_) {}

    // 全屏遮罩（默认开启，可通过 config.noGlobalLoading 或 headers.noGlobalLoading 关闭）
    try {
      const disableGlobalLoading = config.noGlobalLoading === true || (config.headers || {}).noGlobalLoading === true;
      if (!disableGlobalLoading && typeof window !== 'undefined') {
        const overlay = getOverlayState()
        overlay.count += 1
        if (!overlay.instance) {
          overlay.instance = ElLoading.service({
            fullscreen: true,
            lock: true,
            text: '请稍候...',
            background: 'rgba(0, 0, 0, 0.35)'
          })
        }
        Object.defineProperty(config, '__usesGlobalLoading', {
          value: true,
          enumerable: false,
          configurable: true,
          writable: true,
        })
      } else {
        Object.defineProperty(config, '__usesGlobalLoading', {
          value: false,
          enumerable: false,
          configurable: true,
          writable: true,
        })
      }
    } catch (_) {}

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
aiService.interceptors.response.use(
  response => {
    try {
      const btnLoading = response?.config?.__btnLoading;
      btnLoading && btnLoading.close && btnLoading.close();
      if (response?.config && '__btnLoading' in response.config) {
        response.config.__btnLoading = null;
      }
    } catch (_) {}
    // 关闭全屏遮罩（若启用）
    try {
      if (response?.config?.__usesGlobalLoading) {
        const overlay = getOverlayState()
        overlay.count = Math.max(overlay.count - 1, 0)
        if (overlay.count === 0 && overlay.instance) {
          overlay.instance.close()
          overlay.instance = null
        }
        response.config.__usesGlobalLoading = false
      }
    } catch (_) {}
    return response.data
  },
  error => {
    console.error('AI服务请求错误:', error)
    try {
      const btnLoading = error?.config?.__btnLoading;
      btnLoading && btnLoading.close && btnLoading.close();
      if (error?.config && '__btnLoading' in error.config) {
        error.config.__btnLoading = null;
      }
    } catch (_) {}
    // 关闭全屏遮罩（若启用）
    try {
      if (error?.config?.__usesGlobalLoading) {
        const overlay = getOverlayState()
        overlay.count = Math.max(overlay.count - 1, 0)
        if (overlay.count === 0 && overlay.instance) {
          overlay.instance.close()
          overlay.instance = null
        }
        error.config.__usesGlobalLoading = false
      }
    } catch (_) {}
    
    // 统一错误处理
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，跳转到登录页
          window.location.href = '/login'
          break
        case 403:
          // 无权限
          console.error('无权限访问AI服务')
          break
        case 404:
          // 服务不存在
          console.error('AI服务不存在')
          break
        case 500:
          // 服务器错误
          console.error('AI服务内部错误')
          break
        default:
          console.error('AI服务未知错误')
      }
    } else if (error.code === 'ECONNABORTED') {
      console.error('AI服务请求超时')
    } else {
      console.error('AI服务网络错误')
    }
    
    return Promise.reject(error)
  }
)

export default aiService